package com.deluxelx.soul.inn.service.file.impl;

import cn.hutool.core.util.StrUtil;
import com.deluxelx.soul.inn.bean.user.User;
import com.deluxelx.soul.inn.service.file.FileStrategyConfig;
import com.deluxelx.soul.inn.service.file.IFileStrategy;
import com.deluxelx.soul.inn.service.user.UserDaoExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import static com.deluxelx.soul.inn.common.constant.FileType.USER_AVATAR;

/**
 * 用户头像文件
 *
 * @author liaozihao
 * @date 2024-04-30 9:15
 */
@Component("userAvatarStrategy")
@Slf4j
public class UserAvatarStrategy extends FileStrategyConfig implements IFileStrategy {

    @Resource
    private UserDaoExt userDaoExt;

    @Override
    public Boolean upload(MultipartFile file, String primaryId) {
        try {
            String url = ossFileUtil.upload(file, USER_AVATAR);
            if (StrUtil.isBlank(url)) {
                return false;
            }
            return userDaoExt.lambdaUpdate()
                    .set(User::getAvatar, url)
                    .eq(User::getId, primaryId)
                    .update();
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return false;
        }
    }

    @PostConstruct
    public void init() {
        fileStrategyMap.put(USER_AVATAR, this);
    }
}
